
Array.prototype.removeByVal = function(val) {
    var idx;
    while ((idx = this.indexOf(val)) >= 0) {
        this.splice(idx, 1);
    }
};

$(document).ready(function() {

    function refreshView() {

        var ul = blockerConfig.blockedUsers.length;
        var $vessel = $('#blocked-list');

        if (blockerConfig.blockedTweetImages) {

            $("#block-image").click();
        }

        $('#block-tips').val(blockerConfig.blockedTips);
        $vessel.find('section').remove();

        if (ul == 0) {
            $vessel.find('p').show();
            return;
        }

        $vessel.find('p').hide();
        for (var i = 0; i < ul; ++i) {
            $vessel.append('<section><div class="username">' + blockerConfig.blockedUsers[i] + '</div><div title="删除" class="delete-op">[X]</div></section>');
        }
    }

    $('#blocked-list').on('click', '.delete-op', function() {
        var username = $(this).parent().find('.username').text().toLowerCase();
        $(this).parent().remove();
        blockerConfig.blockedUsers.removeByVal(username);
        blockerConfig.save();
        refreshView();
    });

    $('#do-block').on('click', function() {
        var un = $('#block-username').val().trim().toLowerCase();
        if (un.length == 0) {
            $('#block-username').focus();
            return;
        }
        if (blockerConfig.blockedUsers.indexOf(un) >= 0) {
            alert('该用户已经被遮蔽~');
            $('#block-username').val('').focus();
            return;
        }
        $('#block-username').val('').focus();
        blockerConfig.blockedUsers.push(un);

        blockerConfig.save();
        refreshView();
    });

    $('#restore').on('click', function() {
        blockerConfig.restore();
        refreshView();
    });

    $('#block-image').on('click', function() {
        blockerConfig.blockedTweetImages = $(this).is(":checked");
        blockerConfig.save();
    });

    $('#block-tips').on('change', function() {
        blockerConfig.blockedTips = $(this).val();
        blockerConfig.save();
    });

    prLoaded.then(function() {
        refreshView();
        $('input').removeAttr('disabled');
        $('textarea').removeAttr('disabled');
    });

});
